package com.dd.keel.core.framework.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 逻辑处理器
 * @author Kevin.XU
 *
 */
public class ServerWorker implements Runnable{

	final static private Logger LOGGER = LoggerFactory.getLogger(ServerWorker.class);
	
	private ServerReqObjQueue serverReqObjQueue;
	private ServerLogicHandler serverLogicHandler;
	
	private boolean isRunning = false;
	private String engineName;
	private int index = -1;
	private Thread currentThread = null;
	
	public ServerWorker(String engineName,int index,ServerLogicHandler serverLogicHandler,ServerReqObjQueue serverReqObjQueue)
	{
		this.engineName = engineName;
		this.index = index;
		this.serverReqObjQueue = serverReqObjQueue;
		this.serverLogicHandler = serverLogicHandler;
	}
	
	public void startup() 
	{
		currentThread = new Thread(this,engineName+"-ServerWorker-"+index);
		currentThread.setPriority(Thread.NORM_PRIORITY);
		currentThread.start();
	}

	public void shutdown()
	{
		isRunning = false;
		currentThread.interrupt();
	}
	
	@Override
	public void run() 
	{
		isRunning = true;
		LOGGER.info( "startup" );
		while(isRunning)
		{
			ServerTaskObj taskObj = null;
			try{
				taskObj = serverReqObjQueue.getReq();
				if(taskObj!=null)
				{
					String sequence = taskObj.getSequenceWithRemoteAddr();
					LOGGER.debug("server::begin to handle request= {},{}",sequence,taskObj.getMsgObj());
					long start_time = System.currentTimeMillis();
					Object responseObj = serverLogicHandler.handle(taskObj.getMsgObj());
					long elapsed = System.currentTimeMillis() - start_time;
					LOGGER.debug("server::handle completed successfully, cost={}, response= {}",elapsed,responseObj);
					taskObj.getSession().write(responseObj);
				}
			}catch(Exception ex){
				LOGGER.error(ex.getMessage(), ex);
				LOGGER.error("server::handle completed failed, request= {}",taskObj.getMsgObj());
			}
		}
		LOGGER.info( "shutdown" );
	}
	
}
